package com.example.springboot1.Service.impl;

import com.example.springboot1.Service.LoginService;
import com.example.springboot1.mapper.LoginMapper;
import com.example.springboot1.pojo.Login;
import com.example.springboot1.pojo.LoginVo;
import com.example.springboot1.pojo.User;
import com.example.springboot1.utils.JwtUtils;
import com.example.springboot1.utils.MD5;
import com.example.springboot1.utils.exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    public LoginMapper loginMapper;
    @Override
    public Login getLoginById(Integer id) {
        return loginMapper.getLoginById(id);
    }

    //登录
    public Login findLogin(String user_name,String user_pwd) {
        return loginMapper.findLogin(user_name,user_pwd);
    }

    //分页
    @Override
    public List<Login> LoginPage(Integer pageNum, Integer pageSize) {
        List<Login> list = loginMapper.LoginPage(pageNum,pageSize);
        return list;
    }

    @Override
    public int InsertLogin(Login login) {
        int i = loginMapper.InsertLogin(login);
        return i;
    }
    @Override
    public int updateLogin(Login login) {
        int i = loginMapper.updateLogin(login);
        return i;
    }
    @Override
    public int deleteLogin (Integer id) {
        return loginMapper.deleteLogin(id);
    }

    //登录的方法
    @Override
    public String login(LoginVo loginVo) {
        //获取登录用户名和密码
        String user_name = loginVo.getUser_name();
        String user_pwd = loginVo.getUser_pwd();
        //用户名和密码非空判断
        if(StringUtils.isEmpty(user_name) || StringUtils.isEmpty(user_pwd)) {
            throw new MyException(201,"用户名密码不能为空");
        }
//        //判断用户名是否正确
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("member_name",user_name);
//        Member login = baseMapper.selectOne(wrapper);
//        //判断查询对象是否为空
//        if(login == null) {   //没有这个用户名
//            throw new MyException(201,"没有此用户名");
//        }
        Login login = loginMapper.findLoginByName(user_name);
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据库密码进行比较
        if(!MD5.encrypt(user_pwd).equals(login.getUser_pwd())) {
            throw new MyException(201,"密码错误");
        }
        //登录成功，生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(login.getId(), login.getUser_name());
        return jwtToken;
    }
}
